package com.ns.scs.comments.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ns.core.current.config.SymbolsMark;
import com.ns.core.enums.GeneralEnum;
import com.ns.core.utils.bean.ServiceUtil;
import com.ns.core.utils.sg.ResultError;
import com.ns.scs.comments.dto.CommentsPageDto;
import com.ns.scs.comments.entry.CommentsEntry;
import com.ns.scs.comments.mapper.CommentsMapper;
import com.ns.scs.comments.vo.CommentsVO;
import com.ns.scs.my.vo.MyCommentsVO;
import com.ns.scs.props.entry.PropEntry;
import com.ns.scs.props.mapper.PropEntryMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 资源评论接口业务实现
 *
 * @author lw
 * @since 2024/09/23
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, CommentsEntry> implements ICommentsService {
    private final CommentsMapper mapper;

    @Override
    public Page<CommentsVO> getList(CommentsPageDto dto) {
        return mapper.getList(dto, new Page<>(dto.getCurrent(), dto.getSize()));
    }

    @Override
    public List<CommentsVO> getByResourceId(Long resourceId) {
        List<CommentsVO> comments = mapper.getByResourceId(resourceId);
        if (CollectionUtils.isEmpty(comments)) {
            return comments;
        }
        // 数据分组
        Map<Long, List<CommentsVO>> maps = new HashMap<>();
        List<CommentsVO> roots = new ArrayList<>();
        for (CommentsVO comment : comments) {
            // 处理用户名uname只显示前两位和后两位,中间使用四个*代替
            String uname = comment.getUname();
            if (StringUtils.hasText(uname)) {
                if (uname.length() > 4) {
                    uname = uname.substring(0, 2) + "****" + uname.substring(uname.length() - 2);
                } else {
                    uname = "****";
                }
                comment.setUname(uname);
            }
            if (Objects.isNull(comment.getPid())) {
                // 无父节点
                roots.add(comment);
            } else {
                // 右父节点，父节点map 中
                List<CommentsVO> commentsMap = maps.get(comment.getPid());
                if (CollectionUtils.isEmpty(commentsMap)) {
                    commentsMap = new ArrayList<>();
                }
                commentsMap.add(comment);
                maps.put(comment.getPid(), commentsMap);
            }
        }
        // 数据封装子节点
        dealTree(roots, maps);
        return roots;
    }

    /**
     * 封装子节点树
     *
     * @param roots 父节点
     * @param maps  父子关系
     */
    private void dealTree(List<CommentsVO> roots, Map<Long, List<CommentsVO>> maps) {
        for (CommentsVO root : roots) {
            List<CommentsVO> children = maps.get(root.getId());
            if (!CollectionUtils.isEmpty(children)) {
                dealTree(children, maps);
            }
            root.setChildren(children);
        }
    }

    @Override
    public int thumbsUp(Long id, Long uid) {
        CommentsEntry comment = mapper.selectById(id);
        if (Objects.isNull(comment)) {
            throw new RuntimeException("该评论不存在");
        }
        if (StringUtils.hasText(comment.getLikes())) {
            boolean flag = comment.getLikes().contains(String.valueOf(uid));
            List<String> newLikes = new ArrayList<>(Arrays.asList(comment.getLikes().split(SymbolsMark.COMMA)));
            if (flag) {
                newLikes.remove(String.valueOf(uid));
            } else {
                newLikes.add(String.valueOf(uid));
            }
            comment.setLikes(String.join(SymbolsMark.COMMA, newLikes));
        } else {
            comment.setLikes(String.valueOf(uid));
        }
        return mapper.updateById(comment);
    }

    @Override
    public CommentsVO comment(CommentsEntry entry) {
        PropEntryMapper bean = ServiceUtil.getBean(PropEntryMapper.class);
        PropEntry prop = bean.getByCode(GeneralEnum.DICT.IS_NEED_AUDIT.getKey());
        if (ObjectUtils.isEmpty(prop) || StringUtils.pathEquals(prop.getVal(), SymbolsMark.ZERO_S)) {
            entry.setStatus(SymbolsMark.ONE);
        } else {
            entry.setStatus(SymbolsMark.ZERO);
        }

        if (!mapper.insertOrUpdate(entry)) {
            throw new ResultError("评论失败");
        }
        return mapper.getCommentById(entry.getId());
    }

    @Override
    public List<MyCommentsVO> getByResourceIdAndUidAndType(Long resourceId, Long uid, String type) {
        return mapper.getByResourceIdAndUidAndType(resourceId, uid, type);
    }

    @Override
    public boolean audit(Long id, Integer status) {
        return mapper.audit(id, status);
    }
}
